//
//  SEDoctorDetailViewController.swift
//  SmartEyeForPatient
//
//  Created by QDSG on 2021/4/12.
//

import UIKit

class SEDoctorDetailViewController: SEBaseViewController {
    
    private var viewModel = SEDoctorDetailViewModel()

    init(with doctorId: String) {
        self.viewModel.model.id = doctorId
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        getDoctorDetailInfo()
    }
    
    override func setupUI() {
        super.setupUI()
        
        tableView.parallaxHeader.view = headerView
        tableView.parallaxHeader.height = kDoctorDetailHeaderDefaultHeight
        tableView.parallaxHeader.minimumHeight = UIScreen.navigationBarMaxY
        tableView.parallaxHeader.mode = .fill
        
        headerView.expandHandle = { [weak self] (diff, isExpanded) in
            guard let self = self else { return }
            UIView.animate(withDuration: 0.25, delay: 0, options: .curveLinear) {
                if isExpanded {
                    self.headerView.height += diff
                    self.tableView.parallaxHeader.height += diff
                } else {
                    self.headerView.height = kDoctorDetailHeaderDefaultHeight
                    self.tableView.parallaxHeader.height = kDoctorDetailHeaderDefaultHeight
                }
                self.tableView.contentOffset = CGPoint(x: 0, y: -self.tableView.parallaxHeader.height)
                self.headerView.rotateExpandButton()
            }
        }

        viewModel.updateData = { status in
            switch status {
            case .success:
                self.tableView.isHidden = false
                self.confirmButton.isHidden = false
                self.headerView.updateWithViewModel(self.viewModel)
                self.updateRightItem()
                self.tableView.reloadData()
            case .auth(let msg):
                self.presentLoginViewController(selector: #selector(self.getDoctorDetailInfo)) {
                    SEHUD.showError(message: msg)
                }
            case .failure(let msg):
                SEHUD.showError(message: msg)
            }
        }

        viewModel.followedHandler = { status in
            switch status {
            case .success:
                self.viewModel.model.status = self.viewModel.model.status == 1 ? 2 : 1
                self.updateRightItem()
            case .auth(let msg):
                self.presentLoginViewController(selector: #selector(self.requestFollowedDoctor)) {
                    SEHUD.showError(message: msg)
                }
            case .failure(let msg):
                SEHUD.showError(message: msg)
            }
        }

    }
    
    override func setupNavBar() {
        super.setupNavBar()
        
        tableView.contentOffset = CGPoint(x: 0, y: -tableView.parallaxHeader.height)

    }

    private func updateRightItem() {
        let btn = UIButton(type: .custom)
        btn.widthAnchor.constraint(equalToConstant: 50).isActive = true
        btn.heightAnchor.constraint(equalToConstant: 24).isActive = true
        btn.layer.cornerRadius = 12
        btn.layer.masksToBounds = true
        btn.backgroundColor = Asset.main.color
        let title = viewModel.model.status == 1 ? "已关注" : "关注"
        btn.setTitle(title, for: .normal)
        btn.titleLabel?.font = UIFont.regular(13)
        btn.addTarget(self, action: #selector(rightItemAction), for: .touchUpInside)
        let rightItem = UIBarButtonItem(customView: btn)
        navigationItem.rightBarButtonItem = rightItem
    }

    @objc private func rightItemAction() {
        requestFollowedDoctor()
    }

    // MARK: - getter
    private lazy var headerView: SEDoctorDetailHeaderView = {
        let header = UINib.loadViewFrom(SEDoctorDetailHeaderView.self)
        header.frame = CGRect(x: 0, y: 0, width: UIScreen.screenWidth, height: kDoctorDetailHeaderDefaultHeight)
        header.hospitalPushClosure = {
            self.pushToHospitalDetail()
        }
        return header
    }()
    
    @IBOutlet private weak var tableView: UITableView! {
        didSet {
            tableView.isHidden = true
            tableView.estimatedRowHeight = 44.0
            tableView.backgroundColor = UIColor.background
            tableView.tableFooterView = UIView()
            tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 50 + UIScreen.bottomSafeHeight + 35, right: 0)
            
            tableView.register(SEDoctorDetailServiceCell.nibForCell(),
                               forCellReuseIdentifier: SEDoctorDetailServiceCell.reuseIdentifier())
            tableView.register(SEDoctorDetailCommentCell.nibForCell(),
                               forCellReuseIdentifier: SEDoctorDetailCommentCell.reuseIdentifier())
        }
    }
    
    @IBOutlet private weak var confirmButton: UIButton! {
        didSet {
            confirmButton.isHidden = true
            confirmButton.layer.cornerRadius = confirmButton.height / 2
        }
    }
    
    @IBAction private func confirmAction() {
        pushToOnlineReserve()
    }
}

// MARK: - Navi Push

extension SEDoctorDetailViewController {
    private func pushToHospitalDetail() {
        let vc = SEHospitalDetailViewController(with: viewModel.model.hospitalId ?? "")
        navigationController?.pushViewController(vc, animated: true)
    }

    private func pushToOnlineReserve() {
        let vc = SEOnlineReserveViewController(doctorDetailVM: viewModel)
        vc.title = "就诊信息填写"
        navigationController?.pushViewController(vc, animated: true)
    }

    private func pushToRegistrationChooseNum(model: SERegistrationDoctorShift) {
        let vc = SERegistrationChooseNumController(with: model)
        vc.title = model.doctorName
        navigationController?.pushViewController(vc, animated: true)
    }
}

// MARK: - SEDoctorDetailServiceCellDelegate

extension SEDoctorDetailViewController: SEDoctorDetailServiceCellDelegate {
    func doctorDetailServiceCell(_ cell: SEDoctorDetailServiceCell, didTappedForSwitchService service: SEDoctorDetailServiceType) {
        viewModel.serviceType = service
        let indexPath = tableView.indexPath(for: cell) ?? IndexPath(row: 0, section: 0)
        tableView.reloadRows(at: [indexPath], with: .automatic)
        confirmButton.isHidden = viewModel.serviceType == .reserve
    }
}

// MARK: - UITableViewDataSource

extension SEDoctorDetailViewController: UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return viewModel.numberOfRowsInSection(section: section)
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        switch indexPath.section {
        case 0:
            let cell = tableView.dequeueReusableCell(withIdentifier: SEDoctorDetailServiceCell.reuseIdentifier()) as! SEDoctorDetailServiceCell
            cell.delegate = self
            cell.reserveViewDelegate = self
            cell.dateViewDelegate = self
            cell.updateWithViewModel(viewModel)
            return cell
        case 1:
            let cell = tableView.dequeueReusableCell(withIdentifier: SEDoctorDetailCommentCell.reuseIdentifier()) as! SEDoctorDetailCommentCell
            cell.updateWithViewModel(viewModel.commentDetail(indexPath: indexPath))
            return cell
        default:
            return UITableViewCell()
        }
    }
}

extension SEDoctorDetailViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let header = UINib.loadViewFrom(SEDoctorDetailSectionHeader.self)
        header.titleLabel.text = section == 0 ? "选择医生服务" : "患者评价"
        return header
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return nil
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 50
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 10
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return viewModel.heigthForRow(indexPath: indexPath)
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if scrollView.contentOffset.y >= -(scrollView.parallaxHeader.minimumHeight) {
            navigationItem.title = viewModel.model.name
            let alpha = scrollView.contentOffset.y >= 0 ? 0 : abs(scrollView.contentOffset.y) / 100
            headerView.alpha = alpha
        } else {
            navigationItem.title = "医生详情"
            headerView.alpha = 1
        }
    }
}

// MARK: - APIRequest
extension SEDoctorDetailViewController {
    @objc private func getDoctorDetailInfo() {
        viewModel.getDoctorDetailInfo()
    }

    @objc private func requestFollowedDoctor() {
        viewModel.retquestFollowedDoctor()
    }
}

// MARK: - SEDoctorDetailReserveServiceViewDelegate

extension SEDoctorDetailViewController: SEDoctorDetailReserveServiceViewDelegate {
    func doctorDetailReserveServiceViewSectionHeaderTap() {
        tableView.reloadData()
    }
}

// MARK: - SERegistrationDoctorDateViewDelegate

extension SEDoctorDetailViewController: SERegistrationDoctorDateViewDelegate {
    func registrationDoctorDateViewBtnAction(model: SERegistrationDoctorShift) {
        pushToRegistrationChooseNum(model: model)
    }
}
